extends CharacterBody2D

# 移动参数
@export var speed: float = 300.0
@export var acceleration: float = 15.0
@export var friction: float = 15.0
@export var footstep_interval: float = 0.3  # 脚步交替间隔

# 方向枚举 (0=下, 1=右, 2=上, 3=左)
enum Direction {DOWN = 0, RIGHT = 1, UP = 2, LEFT = 3}
# 移动状态 (0=停止, 1=左脚, 2=右脚)
enum MoveState {IDLE = 0, LEFT_FOOT = 1, RIGHT_FOOT = 2}

# 当前状态
var current_direction: Direction = Direction.DOWN
var current_move_state: MoveState = MoveState.IDLE
var is_moving: bool = false
var footstep_timer: float = 0.0

@onready var sprite: Sprite2D = $Sprite2D

func _ready():
	# 确保物理更新模式正确
	set_physics_process(true)
	# 初始状态
	update_visuals()

func _physics_process(delta: float) -> void:
	# 1. 获取输入
	var input_vector = Vector2(
		Input.get_action_strength("move_right") - Input.get_action_strength("move_left"),
		Input.get_action_strength("move_down") - Input.get_action_strength("move_up")
	).normalized()
	
	# 2. 处理移动逻辑
	handle_movement(input_vector, delta)
	
	# 3. 应用物理移动
	var was_on_floor = is_on_floor()
	move_and_slide()
	
	# 4. 更新视觉表现
	update_visuals()

func handle_movement(input_vector: Vector2, delta: float):
	# 方向判定
	if input_vector.length() > 0.1:  # 有输入
		is_moving = true
		
		# 精确方向判定（8方向）
		var angle = input_vector.angle()
		if angle >= -PI/4 and angle < PI/4:
			current_direction = Direction.RIGHT
		elif angle >= PI/4 and angle < 3*PI/4:
			current_direction = Direction.UP
		elif angle >= -3*PI/4 and angle < -PI/4:
			current_direction = Direction.DOWN
		else:
			current_direction = Direction.LEFT
		
		# 脚步动画计时
		footstep_timer += delta
		if footstep_timer >= footstep_interval:
			footstep_timer = 0.0
			current_move_state = MoveState.RIGHT_FOOT if current_move_state == MoveState.LEFT_FOOT else MoveState.LEFT_FOOT
		
		# 计算速度
		var target_velocity = input_vector * speed
		velocity = velocity.lerp(target_velocity, acceleration * delta)
	else:  # 无输入
		is_moving = false
		current_move_state = MoveState.IDLE
		footstep_timer = 0.0
		velocity = velocity.lerp(Vector2.ZERO, friction * delta)

func update_visuals():
	# 确保精灵朝向正确
	sprite.flip_h = false
	sprite.flip_v = false
	
	# 根据方向和状态设置帧（假设精灵表是4x3布局）
	var frame_index = current_direction * 3 + current_move_state
	sprite.frame = frame_index
	
	# 特殊处理：左右方向可以共用同一组动画，只需水平翻转
	if current_direction == Direction.LEFT:
		sprite.flip_h = true
		# 使用右方向的帧
		sprite.frame = Direction.RIGHT * 3 + current_move_state

	# 调试信息（可选）
	print("方向: %d, 状态: %d, 帧: %d" % [current_direction, current_move_state, sprite.frame])
